﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace eCommerce.SagePay
{
    public class TextClean
    {
        public string CleanInput(string strRawText, string strType)
        {

            string strClean = "";
            bool bolHighOrder = false;
            string strCleanedText = "";
            int iCharPos = 1;
            string chrThisChar = "";

            if (strType == "Number")
            {
                strClean = "0123456789.";
                bolHighOrder = false;
            }
            else if (strType == "VendorTxCode")
            {
                strClean = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
                bolHighOrder = false;
            }
            else
            {
                strClean = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'/{}@():?-_&£$=%~<>*+\"" +
                           "\r\n";
                bolHighOrder = true;
            }

            while (iCharPos <= (strRawText).Length)
            {
                //** Only include valid characters **
                chrThisChar = Mid(strRawText, iCharPos, 1);
            }

            if (strClean.IndexOf(chrThisChar) != 0)
            {
                strCleanedText = strCleanedText + chrThisChar;
            }
            else if (bolHighOrder)
            {
                //** Fix to allow accented characters and most high order bit chars which are harmless **
                if (Asc(chrThisChar) >= 191) strCleanedText = strCleanedText + chrThisChar;
            }


            iCharPos = iCharPos + 1;



            return (strCleanedText).Trim();
        }




        private static string Mid(string text, int pos, int i)
        {
            string temp = text.Substring(pos - 1, i);
            return temp;
        }

        public static byte Asc(string src)
        {
            return (System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(src +
            "")[0]);
        }
    }
}
    

